// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use tauri::Manager;
use std::fs;
use std::path::Path;

// 文件操作命令
#[tauri::command]
fn read_file_content(path: String) -> Result<String, String> {
    match fs::read_to_string(&path) {
        Ok(content) => Ok(content),
        Err(e) => Err(format!("读取文件失败: {}", e)),
    }
}

#[tauri::command]
fn write_file_content(path: String, content: String) -> Result<(), String> {
    match fs::write(&path, content) {
        Ok(_) => Ok(()),
        Err(e) => Err(format!("写入文件失败: {}", e)),
    }
}

#[tauri::command]
fn list_directory(path: String) -> Result<Vec<String>, String> {
    match fs::read_dir(&path) {
        Ok(entries) => {
            let mut files = Vec::new();
            for entry in entries {
                if let Ok(entry) = entry {
                    if let Some(name) = entry.file_name().to_str() {
                        files.push(name.to_string());
                    }
                }
            }
            Ok(files)
        }
        Err(e) => Err(format!("读取目录失败: {}", e)),
    }
}

#[tauri::command]
fn create_directory(path: String) -> Result<(), String> {
    match fs::create_dir_all(&path) {
        Ok(_) => Ok(()),
        Err(e) => Err(format!("创建目录失败: {}", e)),
    }
}

#[tauri::command]
fn delete_file(path: String) -> Result<(), String> {
    if Path::new(&path).is_dir() {
        match fs::remove_dir_all(&path) {
            Ok(_) => Ok(()),
            Err(e) => Err(format!("删除目录失败: {}", e)),
        }
    } else {
        match fs::remove_file(&path) {
            Ok(_) => Ok(()),
            Err(e) => Err(format!("删除文件失败: {}", e)),
        }
    }
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![
            read_file_content,
            write_file_content,
            list_directory,
            create_directory,
            delete_file
        ])
        .setup(|app| {
            let _window = app.get_window("main").unwrap();
            
            // 在 Tauri 1.x 中，窗口样式通过配置文件设置
            
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("运行Tauri应用失败");
}